/**
 *
 */
package hichecker.ui.components.custom_table.table_cell_editor;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
 *
 */
abstract public class AbstractTableCellEditor extends DefaultCellEditor{

	protected JTextField comp;
	protected boolean resetText;

	public AbstractTableCellEditor() {
		super(new JTextField());
		comp = (JTextField) getComponent();
		comp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
			int row, int column) {
		comp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		comp.setText(resetText ? "" : value == null ? "" : "" + value);

		return comp;
	}

	@Override
	public Object getCellEditorValue() {
		return comp.getText();
	}

	@Override
	public boolean isCellEditable(EventObject anEvent) {
		resetText = false;

		// It's a mouseevent, so count the clicks
	    if (anEvent instanceof MouseEvent) {
			return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
	    }

	    // It's a keyevent, so check if it's a key that should start editing
	    if (anEvent instanceof KeyEvent) {

	    	// Get the events key
	    	int keyCode = ((KeyEvent) anEvent).getKeyCode();
	    	char keyChar = ((KeyEvent) anEvent).getKeyChar();

	    	// F2 allowed text is not resetted
	    	if (keyCode == KeyEvent.VK_F2) {
	    		return true;
	    	}

	    	// Letters and digits are allowed, text is resetted
	    	if (Character.isLetterOrDigit(keyChar) || Character.isWhitespace(keyChar)) {
	    		resetText = true;
	    		return true;
	    	}

	    	// Others keys are not allowed
	    	return false;

	    }

	    // All other events are not allowed
	    return false;
	}

	@Override
	public boolean stopCellEditing() {
		boolean valid = isValidInput();
		if (!valid) {
			comp.setBorder(BorderFactory.createLineBorder(Color.RED));
			return false;
		}
		comp.setText(getModifiedInput());
		fireEditingStopped();
		return true;
	}

	abstract public boolean isValidInput();

	abstract protected String getModifiedInput();

}
